//
//  ServiceHeadlineView.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2018/10/31.
//  Copyright © 2018年 DUONIU_MAC. All rights reserved.
//

import UIKit

@objc protocol ServiceHeadlineViewDelegate {
    @objc optional func selectItem(index:Int) //选择标签
    @objc optional func selectNews(model:ServiceNewsModel) //选择新闻
}

class ServiceHeadlineView: UIView {

    weak var delegate : ServiceHeadlineViewDelegate?
    
    var titleArray = [String]() {
        didSet{
            headView.dataArray = titleArray
        }
    }
    
    var urlString : String! {
        didSet{
            self.getData(url: urlString)
        }
    }
    
    fileprivate let cellId = "headLineCell"
    fileprivate var dataArray = [ServiceNewsModel]()
    fileprivate var tableView : UITableView!
    
    let headView = TitleHeadView()
    
    fileprivate var page = 1 //页数
    
    init() {
        super.init(frame: .zero)
        
        headView.delegate = self
        self.addSubview(headView)
        
        tableView = UITableView.init(frame: .zero, style: .plain)
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.showsVerticalScrollIndicator = false
        tableView.register(ServiceNewsCell.self, forCellReuseIdentifier: cellId)
        self.addSubview(tableView)
        
        headView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(RATIO_H(maxNum: 40))
        }
        
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(headView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        
        KMTool.setRefresh(with: tableView, headerAction: {[weak self] in
            
            self?.page = 1
            self?.getData(url: (self?.urlString)!)
            
        }) {[weak self] in
            
            self?.getData(url: (self?.urlString)! + "/p\(self!.page)")
        }
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: 获取数据
    fileprivate func getData(url:String) {
        
        //读取服务新闻
        if self.dataArray.count == 0 {
            if NSKeyedUnarchiver.unarchiveObject(withFile: serviceNewsData) != nil {
                
                self.dataArray = NSKeyedUnarchiver.unarchiveObject(withFile: serviceNewsData) as! [ServiceNewsModel]
                self.tableView.reloadData()
            }
        }
        
        KMTool.requestGetData(URLString: url, parameters: nil, success: { (data) in
            
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            
            let elements = ["//ul[@class='new-list']/li/a","//ul[@class='new-list']/li/a/h3","//ul[@class='new-list']/li/a/p","//ul[@class='new-list']/li/a/time"]
            let attributes = ["href","text","text","text"]
            let keys = ["href","title","text","time"]
            let array = KMTool.htmlToModel(data: data, elements: elements, attributes: attributes, keys: keys)
            
            if array.count == 0 {
                return
            }else{
                if self.page == 1 {
                    self.dataArray.removeAll()
                }
                self.page += 1
            }
            
            for item in array {
                let model = ServiceNewsModel.setModel(with: item)
                self.dataArray.append(model)
            }
            
            if self.page == 2 {
                NSKeyedArchiver.archiveRootObject(self.dataArray, toFile: serviceNewsData) //缓存服务新闻
            }
            
            self.tableView.reloadData()
            
        }) {
            
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
        }
    }

}

extension ServiceHeadlineView : UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        return RATIO_H(maxNum: 110)
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? ServiceNewsCell
        cell?.model = dataArray[indexPath.row]
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        self.delegate?.selectNews!(model: dataArray[indexPath.row])
    }
    
}

extension ServiceHeadlineView : TitleHeadViewDelegate {
    
    //MARK: 选择标签
    func selectItem(index: Int) {
        
        self.delegate?.selectItem!(index: index)
    }
    
}
